﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BYFW.WebBase;
using BYFW.DAL;
using System.Web.UI;
using BYFW.SFL;
using BYFW.BOL;
using System.Text.RegularExpressions;
using System.IO;
using BYFW.Encrypt;

namespace LDSP.BRL
{
    public class BasePage : BYFW.WebBase.BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);
                this.RedirectBefore();
                g_pageInfo = PageInfo.GetPageInfo(this);
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        public static object s_lock = new object();

        protected bool needCachePageInfo = false;

        protected PageInfo g_pageInfo = null;

        protected IDBOP DefaultDB
        {
            get { return new BaseEntity().DB; }
        }

        public SystemUser LoginAdmin
        {
            get
            {
                return this.Session["LoginAdmin"] as SystemUser;
            }
            set
            {
                this.Session["LoginAdmin"] = value;
            }
        }

        public EnterpriseUser LoginUser
        {
            get
            {
                return this.Session["LoginUser"] as EnterpriseUser;
            }
            set
            {
                this.Session["LoginUser"] = value;
            }
        }
        

        /// <summary>
        /// 本项目默认的updatepanel
        /// </summary>
        public override UpdatePanel ScriptPanel
        {
            get
            {
                Control ctrl = this.FindControl("pnl_script");
                if (ctrl is UpdatePanel)
                    return (UpdatePanel)ctrl;
                else
                    return null;
            }
        }

        /// <summary>
        /// 获取数据中的数字，默认为0
        /// </summary>
        /// <param name="origin"></param>
        /// <returns></returns>
        public int GetInt(object origin)
        {
            if (origin == null)
            {
                return 0;
            }
            return CommonOP.GetInt(origin.ToString(), false);
        }
        /// <summary>
        /// 获取数字字符串为数字，默认为0
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public double GetDouble(object origin)
        {
            if (origin == null)
            {
                return 0;
            }
            return CommonOP.GetDouble(origin.ToString(), false);
        }
        /// <summary>
        /// 截断长字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public string Ellipsis(string origin, int length)
        {
            return CommonOP.Ellipsis(origin, length);
        }
        /// <summary>
        /// 检查输入的字符长度
        /// </summary>
        /// <param name="name">字段名称</param>
        /// <param name="str">字段值</param>
        /// <param name="length">最大长度</param>
        public void CheckLength(string name, string str, int length)
        {
            if (System.Text.Encoding.ASCII.GetByteCount(str) > length)
            {
                throw new CustomException(string.Format("【{0}】最多输入{1}个字符", name, length));
            }
        }
        /// <summary>
        /// 输入的字符串是否是符合适合用作名字：只包含字母，数字以及下划线和-
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool IsName(string input)
        {
            string pat = @"^[()\[\]0-9A-Za-z_\-\u4e00-\u9fa5]+$";
            Regex reg = new Regex(pat);
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPwd"></param>
        /// <param name="validateCode"></param>
        /// <returns></returns>
        protected bool Login(string userName, string userPwd, string validateCode, int enterpriseID)
        {
            //if (this.Session["ValidateImg"] == null)
            //{
            //    this.JSAlert("当前页面已过期！");
            //    return false;
            //}
            //string vcode = this.Session["ValidateImg"].ToString().ToLower();
            //if (validateCode.Trim().ToLower() != vcode)
            //{
            //    this.JSAlert("验证码输入错误！");
            //    return false;
            //}
            string superUser = System.Configuration.ConfigurationManager.AppSettings["user"];
            string superPwd = System.Configuration.ConfigurationManager.AppSettings["pwd"];
            if (enterpriseID == 0)
            {
                SystemUser su = new SystemUser();
                su.GetProperties(userName);
                if (su.Password == userPwd)
                {
                    LoginAdmin = su;
                    LoginUser = null;
                    return true;
                }
                else if (superUser.ToLower() == userName.Trim().ToLower() && superPwd == userPwd)
                {
                    LoginAdmin = new SystemUser();
                    LoginAdmin.IsSuper = true;
                    LoginUser = null;
                    return true;
                }
                else
                {
                    this.JSAlert("用户名或密码错误！");
                }
            }
            else
            {
                EnterpriseUser eu = new EnterpriseUser();
                eu.GetPropertiesByEnterpriseID(userName, enterpriseID);
                if (eu.Password == userPwd)
                {
                    if (eu.IsValid)
                    {
                        LoginUser = eu;
                        LoginAdmin = null;
                        return true;
                    }
                    else
                    {
                        this.JSAlert("用户已失效，请与系统管理员联系！");
                    }
                }
                else
                {
                    this.JSAlert("用户名或密码错误！");
                }
            }
            return false;
        }

        /// <summary>
        /// 根据用户判断并进行页面跳转
        /// </summary>
        public override void RedirectBefore()
        {
            //todo remove
            string dev = System.Configuration.ConfigurationManager.AppSettings["develop"];
            if (dev != "true")
            {
                this.GoToLogin();
            }
            if (this.LoginUser == null)
            {
                //todo   this.GoToLogin();
            }
        }
        /// <summary>
        /// 跳转到登录页
        /// </summary>
        public virtual void GoToLogin()
        {
            //this.JSRedirect(this.BU + "/Login.aspx", true, true);
            this.Response.Redirect("~/UI/login.aspx", true);
        }
        /// <summary>
        /// 登出
        /// </summary>
        public virtual void Logout()
        {
            this.LoginAdmin = null;
            this.LoginUser = null;
            this.GoToLogin();
        }
        /// <summary>
        /// 列表显示页面，初始化页面的过滤条件控件
        /// </summary>
        public void JSInitFilterControls()
        {
            this.JS(@"$(function(){initFilterControls();})");
        }
        /// <summary>
        /// 设置页面日期文本框就只读
        /// </summary>
        /// <param name="clientID"></param>
        public void JSSetDateTimeReadOnly(string clientID)
        {
            this.JS(string.Format("setReadOnly('{0}')", clientID));
        }

        protected System.Data.DataTable TestData(int rowCount,params string[] fields)
        {
            System.Data.DataTable res = new System.Data.DataTable();
            for (int i = 0; i < fields.Length; i++)
            {
                System.Data.DataColumn dc = new System.Data.DataColumn();
                dc.ColumnName = fields[i];
                res.Columns.Add(dc);
            }
            for (int i = 0; i < rowCount; i++)
            {
                System.Data.DataRow dr = res.NewRow();
                for (int j = 0; j < fields.Length; j++)
                {
                    dr[j] = fields[j] + "_" + i;
                }
                res.Rows.Add(dr);
            }
            return res;
        }

        /// <summary>
        /// 页面上获取组合条件
        /// </summary>
        /// <param name="originCond"></param>
        /// <param name="appendCond"></param>
        /// <param name="isAnd"></param>
        /// <returns></returns>
        protected string AppendCondition(string originCond, string appendCond, bool isAnd)
        {
            return originCond == "" ? appendCond : ("(" + originCond + (isAnd ? " and " : " or ") + appendCond + ")");
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="fileName"></param>
        /// <param name="downloadFile"></param>
        protected void StartDownload(string fileName, string downloadFile)
        {
            if (fileName == "" || !File.Exists(downloadFile))
            {
                this.JSAlert("文件不存在！");
                return;
            }
            this.Context.Response.Buffer = true;
            this.Context.Response.Clear();
            this.Context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
            this.Context.Response.ContentType = "application/zip";
            this.Context.Response.WriteFile(downloadFile);
            this.Context.Response.End();
        }

        /// <summary>
        /// 获取下载法规的JS方法表达式
        /// </summary>
        /// <param name="codification"></param>
        /// <returns></returns>
        protected string GetDownloadJSString(Codification codification)
        {
            return string.Format("javascript:downloadFile(window,'{0}','{1}')", Base64.Encrypt(codification.ID.ToString()), this.BU);
        }
    }
}